package com.github.xzb617.client.flow.metric;

import com.github.xzb617.client.base.props.ClientProperties;
import com.github.xzb617.client.base.lb.ServerLoadBalanceFactory;
import com.github.xzb617.client.flow.core.statics.Statics;
import com.github.xzb617.rpc.LoadBalanceCaller;
import com.github.xzb617.rpc.loadbalancer.factory.LbBeanCreatedException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 向服务端发送 流量Metric 信息
 * @author xzb617
 */
@Component
public class MetricService {

    @Value("${spring.application.name}")
    private String applicationName;

    private final ClientProperties clientProperties;
    private final LoadBalanceCaller loadBalanceCaller;

    public MetricService(ClientProperties clientProperties) throws LbBeanCreatedException {
        this.clientProperties = clientProperties;
        this.loadBalanceCaller = ServerLoadBalanceFactory.createLoadBalanceRpcBroker(clientProperties);
    }

    public void reportMetric() {
        // 收集当前时间所在分钟内的限流指标
        Map<String, String> params = Statics.collectMetricsInMinute();
        // 获取AppId和InstanceId
        params.put("appId", this.applicationName);
        params.put("instanceId", this.clientProperties.getInstanceId());
        // 上报
        this.loadBalanceCaller.lbPost("/clients/flow/metric", params, new HashMap<>(0), Integer.class);
    }
}
